package com.jxdinfo.hussar.example.tsgl.bookflow.service.impl;

import com.jxdinfo.hussar.support.mp.base.service.impl.HussarServiceImpl;
import com.jxdinfo.hussar.support.datasource.annotations.HussarDs;
import com.jxdinfo.hussar.support.exception.HussarException;
import com.jxdinfo.hussar.platform.core.utils.HussarUtils;
import com.jxdinfo.hussar.example.tsgl.bookflow.model.Bookflow;
import com.jxdinfo.hussar.example.tsgl.bookflow.service.BookflowService;
import com.jxdinfo.hussar.example.tsgl.bookflow.dao.BookflowMapper;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jxdinfo.hussar.workflow.manage.engine.TaskEngineService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxdinfo.hussar.common.tfmodel.TfModelEnum;
import com.jxdinfo.hussar.common.security.BaseSecurityUtil;
import com.jxdinfo.hussar.support.transaction.core.annotation.HussarTransactional;
import com.jxdinfo.hussar.workflow.engine.response.BpmResponseResult;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.jxdinfo.hussar.support.mp.base.query.generator.SingleTableQueryGenerator;
import java.util.HashMap;
import com.jxdinfo.hussar.support.mp.base.query.generator.superquery.SuperQueryGenerator;
import org.springframework.aop.framework.AopContext;
import java.util.ArrayList;
import com.jxdinfo.hussar.platform.core.base.apiresult.ApiResponse;
import com.jxdinfo.hussar.example.tsgl.bookflow.dto.BookflowDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import com.jxdinfo.hussar.workflow.engine.constant.BpmConstant;
import com.jxdinfo.hussar.example.tsgl.bookflow.vo.BookflowPageVO;
import java.util.Map;
import com.jxdinfo.hussar.workflow.manage.engine.InstanceEngineService;

/**
 * 图书管理流程服务实现类
 */
@Service("tsgl.bookflow.BookflowServiceImpl")
@HussarDs("master")
public class BookflowServiceImpl extends HussarServiceImpl<BookflowMapper, Bookflow> implements BookflowService {

    private static final Logger logger = LoggerFactory.getLogger(BookflowServiceImpl.class);

    private static final String RETURN_CODE = "0";

    @Override
    @HussarTransactional
    public ApiResponse<String> flowFormSubmitReject(BookflowDto bookflowDto) {
        Bookflow bookflow = bookflowDto.getFormdata();
        try {
            this.saveOrUpdate(bookflow);
            String returnCode = ((BookflowService) AopContext.currentProxy()).formsubmitreject(bookflowDto, String.valueOf(bookflow.getId()));
            if (BpmConstant.SUCCESS_CODE.equals(returnCode)) {
                return ApiResponse.success(TfModelEnum.TF_PROCESS_FORM_WAS_SUCCESSFULLY_SUBMITTED.getMessage());
            } else {
                throw new HussarException(TfModelEnum.TF_FAILED_TO_SUBMIT_THE_PROCESS_FORM.getMessage());
            }
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    @HussarTransactional
    @HussarDs("master")
    public String formsubmitreject(BookflowDto bookflowDto, String businessKey) {
        if (HussarUtils.isEmpty(BaseSecurityUtil.getUser())) {
            throw new HussarException(TfModelEnum.TF_FAILED_T0_OBTAIN_USER_INFORMATION.getMessage());
        }
        Map<String, String> appointMap = new HashMap<>();
        Map<String, Object> variable = new HashMap<>();
        try {
            String taskId = bookflowDto.getTaskId();
            String comment = bookflowDto.getComment();
            if (bookflowDto.getFlowSelect() == null) {
                appointMap.put(BpmConstant.STATIC_APPOINT_ASSIGNEE, bookflowDto.getParticipantSelect());
            } else {
                appointMap.put(bookflowDto.getFlowSelect(), bookflowDto.getParticipantSelect());
                variable.put(BpmConstant.BPM_NEXT_NODE, bookflowDto.getFlowSelect());
            }
            if (bookflowDto.getSelectBranches() != null) {
                List<String> nextNodeIds = new ArrayList<>();
                for (Map<String, String> map : bookflowDto.getSelectBranches()) {
                    appointMap.put(map.get("flowSelect"), map.get("participants"));
                    nextNodeIds.add(map.get("flowSelect"));
                }
                variable.put(BpmConstant.BPM_NEXT_NODE, String.join(",", nextNodeIds));
            }
            // 判断是否设置会签
            if (bookflowDto.getMultiType() != null) {
                variable.put(BpmConstant.MULTI_TYPE, bookflowDto.getMultiType());
                variable.put(BpmConstant.MULTI_FINISH_CONDITION, bookflowDto.getMultiFinishCondition());
            }
            String processDefinitionKey = bookflowDto.getProcessDefinitionKey();
            String userId = String.valueOf(BaseSecurityUtil.getUser().getId());
            if (HussarUtils.isEmpty(taskId)) {
                BpmResponseResult startResult;
                startResult = InstanceEngineService.startProcessInstanceByKey(processDefinitionKey, userId, businessKey, null);
                if (BpmConstant.SUCCESS_CODE.equals(startResult.getCode())) {
                    taskId = (String) startResult.getResult().getJSONObject(0).get("taskId");
                } else {
                    throw new HussarException(TfModelEnum.TF_FAILED_TO_CREATE_A_START_NODE.getMessage());
                }
            }
            BpmResponseResult bpmResponseResult = TaskEngineService.completeLeapTask(taskId, userId, appointMap, null, comment, variable);
            return bpmResponseResult.getCode();
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    public ApiResponse<Bookflow> formQuery(String id) {
        try {
            return ApiResponse.success(this.getById(id));
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }

    @Override
    public ApiResponse<BookflowPageVO> hussarQueryPage(Page<Bookflow> page) {
        try {
            Page<Bookflow> pager = new Page<>(page.getCurrent(), page.getSize());
            Map<String, String[]> parameterMap = new HashMap<>();
            String[] orderParameter = new String[1];
            if (page.orders() != null) {
                for (OrderItem orderItem : page.orders()) {
                    if (orderItem.isAsc()) {
                        orderParameter[0] = orderItem.getColumn() + ",asc;";
                    } else {
                        orderParameter[0] = orderItem.getColumn() + ",desc;";
                    }
                }
            }
            parameterMap.put("orderRule", orderParameter);
            BookflowPageVO bookflowPageVO = new BookflowPageVO();
            // 查询条件构造器,将排序条件封装成QueryWrapper
            SingleTableQueryGenerator singleTableQueryGenerator = new SingleTableQueryGenerator();
            QueryWrapper<Bookflow> queryWrapper = singleTableQueryGenerator.initQueryWrapper(new Bookflow(), parameterMap);
            List<Bookflow> list = this.page(pager, queryWrapper).getRecords();
            bookflowPageVO.setData(list);
            bookflowPageVO.setCount(pager.getTotal());
            bookflowPageVO.setCode(RETURN_CODE);
            return ApiResponse.success(bookflowPageVO);
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }

    @Override
    public ApiResponse<BookflowPageVO> hussarQueryPage_order_custom(Page<Bookflow> page) {
        try {
            Page<Bookflow> pager = new Page<>(page.getCurrent(), page.getSize());
            Map<String, String[]> parameterMap = new HashMap<>();
            String[] orderParameter = new String[1];
            if (page.orders() != null) {
                for (OrderItem orderItem : page.orders()) {
                    if (orderItem.isAsc()) {
                        orderParameter[0] = orderItem.getColumn() + ",asc;";
                    } else {
                        orderParameter[0] = orderItem.getColumn() + ",desc;";
                    }
                }
            }
            parameterMap.put("orderRule", orderParameter);
            BookflowPageVO bookflowPageVO = new BookflowPageVO();
            // 查询条件构造器,将排序条件封装成QueryWrapper
            SingleTableQueryGenerator singleTableQueryGenerator = new SingleTableQueryGenerator();
            QueryWrapper<Bookflow> queryWrapper = singleTableQueryGenerator.initQueryWrapper(new Bookflow(), parameterMap);
            List<Bookflow> list = this.page(pager, queryWrapper).getRecords();
            bookflowPageVO.setData(list);
            bookflowPageVO.setCount(pager.getTotal());
            bookflowPageVO.setCode(RETURN_CODE);
            return ApiResponse.success(bookflowPageVO);
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }
}
